import {createNextTickOnce} from '@/utils';
import {useEffect, useMemo, useRef, useState} from 'react';
import { useCall } from '.';

function useLocalState(name, initialValue = null) {
  const [state, setState] = useState(sessionStorage.getItem(name) ?? JSON.stringify(initialValue));

  const {current: onStore} = useRef(createNextTickOnce(() => {
    const val = sessionStorage.getItem(name);
    if (state !== val) setState(val);
  }));

  useEffect(() => {
    window.addEventListener('storage', onStore);
    return () => {
      window.removeEventListener('storage', onStore);
    };
  }, []);

  const update = useCall((newValue) => {
    try {
      newValue = JSON.stringify(newValue)
    } catch (e) {
      newValue = 'null'
    }
    sessionStorage.setItem(name, newValue);
    setState(newValue);
  });

  return useMemo(() => {
    try {
      return [JSON.parse(state), update];
    } catch (e) {
      return [null, update];
    }
  }, [state]);
}

export default useLocalState;
